﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Innova.Microfinanzas.Business.UsersAndSecurity;
using Innova.Microfinanzas.BusinessEntities;
using Infragistics.Win.UltraWinTree;
using System.IO;
using Infragistics.Win.UltraMessageBox;
using MyCommerce.ManagementBase.Common.Base.Common;
using Infragistics.Win.UltraWinToolbars;
using System.Resources;
using System.Reflection;
using Infragistics.Win.UltraWinStatusBar;

namespace MyCommerce.Common.CommerceClient
{
    public partial class MainClient : BaseForm
    {
        public MainClient(List<Command> colCommandsToLoad)
        {
            InitializeComponent();
            LoadCommandsToTree(colCommandsToLoad);             
        }

        public override void ShowCalculatorControl()
        {
            ShowCalculator();
        }

        public event EventHandler OnBlocking;
        public event EventHandler OnClosingSession;

        public bool mustCLoseDirect = false;

        public User ObjUserLoged
        {
            get;
            set;
        }

        private void LoadCommandsToTree(List<Command> colCommands)
        {
            Context.ColCommandsAvailable = colCommands;
            ultraTree1.Nodes.Clear();
            List<UltraTreeNode> nodes = ConvertFromDbCommans(colCommands);
            foreach (UltraTreeNode objNode in nodes)
            {
                ultraTree1.Nodes.Add(objNode);
            }
        }

        private List<UltraTreeNode> ConvertFromDbCommans(List<Command> commands)
        {
            List<Command> colCommandsToLoad = new List<Command>(commands);
            colCommandsToLoad.RemoveAll(objFilter => objFilter.Visible == false);
            List<Command> roots = GetRootCommands(colCommandsToLoad);
            List<UltraTreeNode> nodes = new List<UltraTreeNode>();

            foreach (Command root in roots)
            {
                UltraTreeNode nCmd = new UltraTreeNode(root.CommandKey, root.Title);
                if (!string.IsNullOrEmpty(root.Type))
                    nCmd.Tag = root;
                else
                    nCmd.Tag = null;
                nodes.Add(nCmd);
                AddCommandToTreeNode(colCommandsToLoad, root, nCmd.Nodes);
            }
            return nodes;
        }

        private void AddCommandToTreeNode(List<Command> commands, Command root, TreeNodesCollection treeCommand)
        {
            List<Command> children = GetChildCommans(root, commands);
            foreach (Command child in children)
            {
                UltraTreeNode nCmd = new UltraTreeNode(child.CommandKey, child.Title);
                if (!string.IsNullOrEmpty(child.Type))
                    nCmd.Tag = child;
                else
                    nCmd.Tag = null;
                treeCommand.Add(nCmd);
                List<Command> children1 = GetChildCommans(child, commands);
                if (children1.Count > 0)
                {
                    AddCommandToTreeNode(commands, child, nCmd.Nodes);
                }
            }
        }

        private List<Command> GetChildCommans(Command parent, List<Command> commands)
        {
            List<Command> children = new List<Command>();
            foreach (Command command in commands)
            {
                if (command.Parent == parent.IdCommand)
                {
                    children.Add(command);
                }
            }
            children.Sort((objComp1, objComp2) => objComp1.OrderBy.CompareTo(objComp2.OrderBy));
            return children;
        }

        private List<Command> GetRootCommands(List<Command> commands)
        {
            List<Command> roots = new List<Command>();
            foreach (Command command in commands)
            {
                if (command.Parent == 0)
                {
                    roots.Add(command);
                }
            }

            roots.Sort((objComp1, objComp2) => objComp1.OrderBy.CompareTo(objComp2.OrderBy));
            return roots;
        }

        private void ultraTree1_DoubleClick(object sender, EventArgs e)
        {
            if (ultraTree1.SelectedNodes != null
                && ultraTree1.SelectedNodes.Count > 0)
            {
                if (ultraTree1.SelectedNodes[0].Tag != null)
                {
                    this.Context.InvoqueCommand((Command)ultraTree1.SelectedNodes[0].Tag, false);
                }
            }
        }
        
        private void MainClient_Load(object sender, EventArgs e)
        {
            InitializeRibbon();
            InitializeStatusBar();
        }

        private void InitializeStatusBar()
        {
            UltraStatusPanel panelUser = new UltraStatusPanel();
            panelUser.Text = "Usuario: " + ObjUserLoged.UserName;
            panelUser.SizingMode = PanelSizingMode.Automatic;
            panelUser.Appearance.Image = imgListMenu.Images["User.png"];

            UltraStatusPanel panelStore = new UltraStatusPanel();
            panelStore.Text = ObjUserLoged.StoreName;
            panelStore.SizingMode = PanelSizingMode.Automatic;
            panelStore.Appearance.Image = imgListMenu.Images["Clipboard.png"];

            UltraStatusPanel panelDealerStore = new UltraStatusPanel();
            panelDealerStore.Text = ObjUserLoged.DealerStoreName;
            panelDealerStore.SizingMode = PanelSizingMode.Automatic;
            panelDealerStore.Appearance.Image = imgListMenu.Images["Home.png"];           

            UltraStatusPanel panelDate = new UltraStatusPanel();
            panelDate.Text = "Fecha: " + DateTime.Today.Date.ToShortDateString();
            panelDate.SizingMode = PanelSizingMode.Automatic;
            panelDate.Appearance.Image = imgListMenu.Images["Calendar.png"];
            panelDate.SizingMode = PanelSizingMode.Automatic;

            UltraStatusPanel panelCurrencyExchange = new UltraStatusPanel();
            panelCurrencyExchange.Text = "Tipo de cambio: " + ObjUserLoged.CurrentCurrencyExchange.ToString("##,###0.00");
            panelCurrencyExchange.SizingMode = PanelSizingMode.Automatic;
            panelCurrencyExchange.Appearance.Image = imgListMenu.Images["Globe.png"];

            statusBarMain.Panels.Add(panelUser);
            statusBarMain.Panels.Add(panelStore);
            statusBarMain.Panels.Add(panelDealerStore);            
            statusBarMain.Panels.Add(panelDate);
            statusBarMain.Panels.Add(panelCurrencyExchange);
        }

        private void InitializeRibbon()
        {
            this.ribbonMain.Ribbon.Visible = true;

            // create some tools that can be sited on the office 2010 style application menu.
            this.CreateApplicationMenu2010Tools();            
            this.InitializeApplicationMenu2010();
        }

        private void CreateApplicationMenu2010Tools()
        {
            // Tools shown in office 2010 style Application Menu
            ButtonTool newBtnToolMenu = new ButtonTool("btnMenu");
            this.ribbonMain.Tools.Add(newBtnToolMenu);
            newBtnToolMenu.SharedProps.AppearancesSmall.Appearance.Image = imgListMenu.Images["Monitor.png"];
            newBtnToolMenu.SharedProps.Caption = "Menu de la aplicación";

            ListTool recentTool = new ListTool("Recent");
            recentTool.DisplayCheckmark = false;
            recentTool.ListToolItems.Add("calc", "Calculadora");
            recentTool.ListToolItems["calc"].Appearance.Image = imgListMenu.Images[6];
            recentTool.ListToolItems.Add("bks", "Respaldos de la BD");
            recentTool.ListToolItems["bks"].Appearance.Image = imgListMenu.Images[18];
            //recentTool.ListToolItems.Add("doc3", "Document3");
            //recentTool.ListToolItems["doc3"].Appearance.Image = imgListMenu.Images[4];
            this.ribbonMain.Tools.Add(recentTool);

            PopupMenuTool popupMenu1 = new PopupMenuTool("btnTools");
            popupMenu1.Settings.PopupStyle = PopupStyle.Menu;
            popupMenu1.SharedProps.AppearancesSmall.Appearance.Image = imgListMenu.Images["Gear.png"];
            popupMenu1.SharedProps.Caption = "Herramientas";
            this.ribbonMain.Tools.Add(popupMenu1);
            popupMenu1.Tools.AddTool("Recent");

            // Tools shown in office 2010 style Application Menu
            ButtonTool newBtnToolAbout = new ButtonTool("btnAbout");
            this.ribbonMain.Tools.Add(newBtnToolAbout);
            newBtnToolAbout.SharedProps.AppearancesSmall.Appearance.Image = imgListMenu.Images["Info.png"];
            newBtnToolAbout.SharedProps.Caption = "Acerca De";

            // Tools shown in office 2010 style Application Menu
            ButtonTool newBtnTool = new ButtonTool("btnCloseSession");
            this.ribbonMain.Tools.Add(newBtnTool);
            newBtnTool.SharedProps.AppearancesSmall.Appearance.Image = imgListMenu.Images["Trash.png"];
            newBtnTool.SharedProps.Caption = "Cerrar sesión";
            // Tools shown in office 2010 style Application Menu
            ButtonTool newBtnTool1 = new ButtonTool("btnBlock");
            this.ribbonMain.Tools.Add(newBtnTool1);
            newBtnTool1.SharedProps.AppearancesSmall.Appearance.Image = imgListMenu.Images["Block.png"];
            newBtnTool1.SharedProps.Caption = "Bloquear";
            // Tools shown in office 2010 style Application Menu
            ButtonTool newBtnTool2 = new ButtonTool("btnExit");
            this.ribbonMain.Tools.Add(newBtnTool2);
            newBtnTool2.SharedProps.AppearancesSmall.Appearance.Image = imgListMenu.Images["Delete.png"];
            newBtnTool2.SharedProps.Caption = "Salir de la aplicación";
        }

        private void InitializeApplicationMenu2010()
        {
            // the office 2010 style application menu is displayed by clicking on the FileMenu
            // button in the upper left corner of the ribbon. This object can be 
            // accessed via the ApplicationMenu2010 property of the Ribbon
            ApplicationMenu2010 appMenu2010 = this.ribbonMain.Ribbon.ApplicationMenu2010;

            // Navigation Menu
            // ============
            //appMenu2010.NavigationMenu.Tools.AddTool("btnMenu");
            appMenu2010.NavigationMenu.Tools.AddTool("btnTools");
            appMenu2010.NavigationMenu.Tools.AddTool("btnAbout");
            appMenu2010.NavigationMenu.Tools.AddTool("btnCloseSession");
            appMenu2010.NavigationMenu.Tools.AddTool("btnBlock");
            appMenu2010.NavigationMenu.Tools.AddTool("btnExit");

        }

        public void ShowCalculator()
        {
            ultraCalculator1.Clear();
            ultraPopupControlContainer1.Show();
            ultraCalculator1.Focus();
        }

        private void ribbonMain_ToolClick(object sender, ToolClickEventArgs e)
        {
            switch (e.Tool.Key)
            {
                case "Recent":
                    switch (((ListTool)(ribbonMain.Tools["Recent"])).SelectedItem.Key)
                    {
                        case "calc":
                            ShowCalculator();
                            break;
                        case "bks":
                            Command commandForm = Context.GetCommand("Bks");
                            object formResult = Context.InvoqueCommandWithParams(commandForm, null, true);
                            break;
                    }
                    break;
                case "btnAbout": 
                    
                    break;
                case "btnCloseSession":
                    if (OnClosingSession != null)
                        OnClosingSession(this, new EventArgs());
                    break;
                case "btnBlock":
                    if (OnBlocking != null)
                        OnBlocking(this, new EventArgs());
                    break;
                case "btnExit":
                    this.Close();
                    break;

            }
        }

        private void MainClient_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!mustCLoseDirect)
            {
                if (Context.ShowQuestionMessageBox("¿Seguro que desea salir de la aplicación?", "My Commerce") == System.Windows.Forms.DialogResult.No)
                {
                    e.Cancel = true;
                }
            }
        }

        private void ribbonMain_BeforeApplicationMenu2010Displayed(object sender, BeforeApplicationMenu2010DisplayedEventArgs e)
        {
            //e.ActiveContentTool = (PopupToolBase)this.ultraToolbarsManager1.Ribbon.ApplicationMenu2010.NavigationMenu.Tools["PopupControlContainerTool"];
        }

        private void btnCloseAndCopy_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(ultraCalculator1.DisplayValue.ToString("##,###0.00"), true);
            ultraPopupControlContainer1.Close();
        }
    }
}
